#!/usr/bin/env python
#
# Author: Bret Taylor (btaylor@gmail.com)
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import parser
import re
import string
import sys


def main():
    for path in sys.argv[1:]:
        try:
            ast = parser.parse(open(path).read().decode("utf-8"))
        except parser.ParseError, e:
            if e.line_number is not None:
                print >> sys.stderr, "%s:%d: %s" % (
                    path, e.line_number, e.message)
            else:
                print >> sys.stderr, "%s: %s" % (path, e.message)
            sys.exit(1)
        print_ast(ast)


def print_ast(ast, name=None, indent=0):
    if isinstance(ast, list):
        print "  " * indent, name or "<base>"
        for child in ast:
            print_ast(child, name, indent + 1)
    elif isinstance(ast, dict):
        children = sorted(k for k in ast.keys() if not k.startswith("node_"))
        print "  " * indent, ast["node_type"]
        for child in children:
            print_ast(ast[child], child, indent + 1)
    else:
        print "  " * indent, name + ":", repr(ast)


if __name__ == "__main__":
    main()
